package org.lds.message.center.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.lds.message.center.common.enums.ErrorEnum;
import org.lds.message.center.common.exception.BusinessException;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Slf4j
public class RestUtil {
    private static final RestTemplate REST_TEMPLATE;

    static {
        OkHttp3ClientHttpRequestFactory requestFactory = new OkHttp3ClientHttpRequestFactory();
        requestFactory.setConnectTimeout(60000);
        requestFactory.setReadTimeout(120000);
        requestFactory.setWriteTimeout(60000);
        REST_TEMPLATE = new RestTemplate(requestFactory);
    }

    public static String post(String url, Object request) {
        return post(url, request, new ParameterizedTypeReference<String>() {
        });
    }

    public static <T> T post(String url, Object request, ParameterizedTypeReference<T> reference) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity httpEntity = new HttpEntity(request, headers);

        try {
            return REST_TEMPLATE.exchange(url, HttpMethod.POST, httpEntity, reference).getBody();
        } catch (Exception e) {
            log.error("post error. url={} request={} cause={}", url, request, e.getMessage());
            throw new BusinessException(ErrorEnum.REST_FAIL);
        }
    }

    public static <T> T get(String url, Map<String, String> param, Class<T> clazz) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        try {
            return MapUtils.isEmpty(param) ?
                    REST_TEMPLATE.getForObject(url, clazz) : REST_TEMPLATE.getForObject(url, clazz, param);
        } catch (Exception e) {
            log.error("get error. url={} param={} cause={}", url, param, e.getMessage());
            return null;
        }
    }

}
